<template>
  <div class="app-container">

    <div class="filter-container">
      <el-select v-model="repairQuery.building" placeholder="请选择区域" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter" @change="queryBuildingChange()">
        <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-select v-model="repairQuery.floor" placeholder="请选择楼层" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in floorOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="repairQuery.rno" placeholder="宿舍号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="repairQuery.goodsName" placeholder="物品名" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="repairQuery.applyBegin" type="datetime" placeholder="申请开始时间" style="width: 200px" class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="repairQuery.applyEnd" type="datetime" placeholder="申请结束时间" style="width: 200px" class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" @keyup.enter.native="handleFilter" />
      <el-select v-model="repairQuery.status" placeholder="请选择状态" clearable style="width: 200px" class="filter-item" @keyup.enter.native="handleFilter">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="repairQuery.phone" placeholder="维修人员电话" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="repairQuery.repairBegin" type="datetime" placeholder="维修开始时间" style="width: 200px" class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" @keyup.enter.native="handleFilter" />
      <el-date-picker v-model="repairQuery.repairEnd" type="datetime" placeholder="维修结束时间" style="width: 200px" class="filter-item" value-format="yyyy-MM-dd HH:mm:ss" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      :row-class-name="tableRowClassName"
    >
      <el-table-column label="区域" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.buildingDesc }}
        </template>
      </el-table-column>
      <el-table-column label="楼层" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.floorDesc }}
        </template>
      </el-table-column>
      <el-table-column label="宿舍号" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.rno }}
        </template>
      </el-table-column>
      <el-table-column label="物品名" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.goodsName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述" width="200">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="申请时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.applyTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.status }}
        </template>
      </el-table-column>
      <el-table-column label="维修员电话" width="210" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="维修时间" width="200" align="center">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.repairTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.remarks }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="medium" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="medium" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="page" :limit.sync="limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" top="6vh">
      <el-form ref="dataForm" :rules="rules" :model="repairVo" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="区域" prop="building">
          <el-select v-model="repairVo.building" placeholder="请选择区域" clearable style="width: 300px;" @change="buildingChange()">
            <el-option v-for="item in buildingOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-select v-model="repairVo.floor" placeholder="请选择楼层" clearable style="width: 300px;">
            <el-option v-for="item in floorOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="宿舍号" prop="rno">
          <el-input v-model="repairVo.rno" />
        </el-form-item>
        <el-form-item label="物品名" prop="goodsName">
          <el-input v-model="repairVo.goodsName" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="repairVo.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="申请时间" prop="applyTime">
          <el-date-picker v-model="repairVo.applyTime" type="datetime" placeholder="请输入申请时间" style="width: 300px;" value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="repairVo.status" placeholder="请选择状态" clearable style="width: 150px" class="filter-item" @keyup.enter.native="handleFilter">
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'update'" label="维修员电话" prop="phone">
          <el-input v-model="repairVo.phone" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'update'" label="维修时间" prop="repairTime">
          <el-date-picker v-model="repairVo.repairTime" type="datetime" placeholder="请输入维修时间" style="width: 300px;" value-format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <el-form-item v-if="dialogStatus === 'update'" label="备注" prop="remarks">
          <el-input v-model="repairVo.remarks" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, remove, save, update, getRepair, buildingList, floorListById } from '@/api/repair'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      listLoading: true,
      total: 0,
      page: 1,
      limit: 10,
      repairQuery: {
        building: '',
        floor: '',
        rno: '',
        goodsName: '',
        status: '',
        phone: '',
        applyBegin: '',
        applyEnd: '',
        repairBegin: '',
        repairEnd: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      repairVo: {
        id: '',
        building: '',
        buildingDesc: '',
        floor: '',
        floorDesc: '',
        roomId: '',
        rno: '',
        goodsName: '',
        description: '',
        applyTime: '',
        status: '',
        phone: '',
        repairTime: '',
        remarks: ''
      },
      dialogFormVisible: false,
      rules: {
        building: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
        floor: [{ required: true, message: '楼层不能为空', trigger: 'blur' }],
        rno: [{ required: true, message: '宿舍号不能为空', trigger: 'blur' }],
        goodsName: [{ required: true, message: '物品名不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
        applyTime: [{ required: true, message: '申请时间不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      statusOptions: [{ label: '申请', key: '0' }, { label: '维修中', key: '1' }, { label: '完成', key: '2' }],
      buildingOptions: [],
      floorDisabled: true,
      floorOptions: [],
      statusMap: { '申请': '0', '维修中': '1', '完成': '2' }
    }
  },
  created() {
    this.getList()
    buildingList().then((response) => {
      this.buildingOptions = response.data
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.page, this.limit, this.repairQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.page = 1
      this.getList()
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.status === '申请') {
        return 'apply-row'
      } else if (row.status === '维修中') {
        return 'repair-row'
      }
      return 'finished-row'
    },
    queryBuildingChange() {
      this.floorOptions = []
      this.repairQuery.floor = ''
      if (this.repairQuery.building !== '') {
        floorListById(this.repairQuery.building).then(response => {
          this.floorOptions = response.data
          this.floorDisabled = false
        })
      }
    },
    buildingChange() {
      this.floorOptions = []
      this.repairVo.floor = ''
      this.repairVo.floorDesc = ''
      if (this.repairVo.building !== '') {
        floorListById(this.repairVo.building).then(response => {
          this.floorOptions = response.data
          this.floorDisabled = false
        })
      }
    },
    handleCreate() {
      this.resetrepairVo()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetrepairVo() {
      this.repairVo = {
        id: '',
        building: '',
        buildingDesc: '',
        floor: '',
        floorDesc: '',
        roomId: '',
        rno: '',
        goodsName: '',
        reason: '',
        applyTime: '',
        status: '',
        phone: '',
        repairTime: '',
        remarks: ''
      }
      this.floorDisabled = true
      this.floorOptions = []
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          save(this.repairVo).then((response) => {
            this.dialogFormVisible = false
            this.list.unshift(response.data)
            this.$notify({
              title: 'Success',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    async handleUpdate(row) {
      // 获取宿舍信息
      const res = await getRepair(row.id)
      this.repairVo = res.data
      // 根据宿舍信息获取楼栋和楼层
      const floorList = await floorListById(this.repairVo.building)
      this.floorDisabled = false
      this.floorOptions = floorList.data
      this.repairVo.status = this.statusMap[this.repairVo.status]
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          update(this.repairVo).then((response) => {
            this.dialogFormVisible = false
            const index = this.list.findIndex(v => v.id === response.data.id)
            this.list.splice(index, 1, response.data)
            this.$notify({
              title: 'Success',
              message: '修改成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
      remove(row.id)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['区域', '楼层', '宿舍号', '物品名', '描述', '申请时间', '状态', '维修员电话', '维修时间', '备注']
        const filterVal = ['buildingDesc', 'floorDesc', 'goodsName', 'description', 'applyTime', 'status', 'phone', 'repairTime', 'remarks']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '维修信息'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style scoped>
::v-deep .el-table .apply-row {
  background: #fff;
}

::v-deep .el-table .repair-row {
  background: oldlace;
}

::v-deep .el-table .finished-row {
  background: #f0f9eb;
}
</style>
